<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="物料id" prop="materialId">
        <el-input
          v-model="queryParams.materialId"
          placeholder="请输入物料id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="物料名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="入库门店" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择入库门店" clearable >
          <el-option
            v-for="item in slectDeptOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="调出门店" prop="exDeptId">
        <el-select v-model="queryParams.exDeptId" placeholder="请选择入库门店" clearable >
          <el-option
            v-for="item in slectDeptOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="stat">
        <el-select v-model="queryParams.stat" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.transfer_stat"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="调拨日期">
        <el-date-picker
          v-model="daterangeTransferTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:inventoryBillJoin:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleCheck"

        >确认调拨</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:inventoryBillJoin:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:inventoryBillJoin:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" show-summary :summary-method="getSummaries" :data="inventoryBillJoinList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="调入门店"  width="120"align="center" prop="deptName" />
      <el-table-column label="物料名称" width="120" align="center" prop="materialName" />
      <el-table-column label="调出门店" width="120" align="center" prop="exDeptName" />
      <el-table-column label="面值" align="center" prop="money" />
      <el-table-column label="单包价格" align="center" prop="price" />
      <el-table-column label="入库包数量" width="120" align="center" prop="packageNum" />
      <el-table-column label="入库张数量" width="120" align="center" prop="sheetNum" />
      <el-table-column label="调拨人" align="center" prop="userName" />
      <el-table-column label="状态" align="center" prop="stat">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.transfer_stat" :value="scope.row.stat"/>
        </template>
      </el-table-column>

      <el-table-column label="调拨时间" align="center" prop="transferTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.transferTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调拨金额" align="center">
        <template slot-scope="scope">
          {{ (scope.row.packageNum *  scope.row.price) + (scope.row.sheetNum * scope.row.money) }}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.stat == 1"
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:inventoryBillJoin:edit']"
          >查看</el-button>
          <el-button
            v-if="scope.row.stat == 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:inventoryBillJoin:edit']"
          >修改</el-button>
          <el-button
           v-if="scope.row.stat == 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:inventoryBillJoin:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出入库--即开票入库明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="调出门店" prop="exDeptId">
          <el-select v-model="form.exDeptId" placeholder="请选择调出门店" @change="outDeptChange">
            <el-option
              v-for="item in slectDeptOptions"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="产品" prop="materialId">
          <el-select v-model="form.materialId" placeholder="请选择产品" @change="materialChange">
              <el-option
                v-for="item in materialList"
                :key="item.materialId"
                :label="item.materialName"
                :value="item.materialId">
              </el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="入库门店" prop="deptId">
          <el-select v-model="form.deptId" placeholder="请选择入库门店">
            <el-option
              v-for="item in slectDeptOptions"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="入库包" prop="packageNum">
          <el-input v-model="form.packageNum" type="number" placeholder="请输入入库包数量" />
        </el-form-item>
        <el-form-item label="入库张" prop="sheetNum">
          <el-input v-model="form.sheetNum" type="number" placeholder="请输入入库张数量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item> -->
        <el-form-item label="状态" prop="stat">
                  <el-radio-group v-model="form.stat" disabled>
                    <el-radio
                      v-for="dict in dict.type.transfer_stat"
                      :key="dict.value"
                      :label="dict.value"
                    >{{dict.label}}</el-radio>
                  </el-radio-group>
                </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="form.stat == 0" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInventoryBillJoin, getInventoryBillJoin, delInventoryBillJoin, addInventoryBillJoin, updateInventoryBillJoin ,check} from "@/api/system/inventoryBillJoin";
import { listDept } from "@/api/system/dept";
import { getSelectList,getMaterialGgl  } from "@/api/system/materialGgl";
import { getInvByDeptIdAndSalesIdAndClassCode,getInventoryGgl,getDeptMaterialInfoByDeptIdAndMaterialId} from "@/api/system/inventoryGgl";
export default {
  name: "InventoryBillJoin",
  dicts: ['transfer_stat'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出入库--即开票入库明细表格数据
      inventoryBillJoinList: [],
      slectDeptOptions:[],
      daterangeTransferTime: [],
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialId: null,
        deptId: null,
        materialName: null,
        packageNum: null,
        sheetNum: null,
        params: {}
      },
      // 表单参数
      form: {
        stat: '0'
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询出入库--即开票入库明细列表 */
    getList() {
      this.loading = true;
      if (null != this.daterangeTransferTime && '' != this.daterangeTransferTime) {
        console.log(this.daterangeTransferTime)
        this.queryParams.params["beginTransferTime"] = this.daterangeTransferTime[0];
        this.queryParams.params["endTransferTime"] = this.daterangeTransferTime[1];
      }
      listInventoryBillJoin(this.queryParams).then(response => {
        this.inventoryBillJoinList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listDept({"parentId":100}).then(response => {
        this.slectDeptOptions = response.data;
      });

    },
    getSummaries(param){
      console.log(param,'getSummaries');
      const { columns, data } = param
      const sums = [];
      columns.forEach((column, index) => {
        //第一个显示为合计
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map((item) => item[column.property])

        if (index == 11) {
          sums[index] = data.reduce((sum,entity) => {
            sum += (Number(entity.packageNum) * ( entity.price)) + (Number(entity.sheetNum) * Number(entity.money))
            return sum;
          },0);
        }

        if(index >=6 && index <=8) {
          //对表格数据进行循环
          values.map((item) => {
            //判断返回的是否为number数据类型
            if (typeof item === 'number' && item !== Infinity && !isNaN(item)) {
              //判断是否为时间戳
              if (item > 160000000000) {
                //若为时间戳则置为--
                sums[index] = '-'
                return
              } else {
                //对number数据进行累加
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr)
                  if (!isNaN(value)) {
                    //解决js计算小数出现小数点后多位数字的问题
                    return Math.floor((prev + curr) * 100) / 100
                  } else {
                    return prev
                  }
                }, 0)
              }
            } else {
              //不为number类型则置为--
              sums[index] = '-'
            }
          })
        }

      })
      return sums

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset('cancel');
    },
    // 表单重置
    reset(cancel) {
      if('cancel' ===cancel){
        this.form = {
        id: null,
        materialId: null,
        deptId: null,
        materialName: null,
        packageNum: null,
        sheetNum: null,
        remark: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      }else {
        this.form = {
        id: null,
        materialId: null,
        deptId: null,
        materialName: null,
        packageNum: null,
        sheetNum: null,
        stat: '0',
        remark: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      }

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeTransferTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    outDeptChange(){
      this.materialList =[];
      this.form.packageNum = null;
      this.form.sheetNum = null;
      this.form.materialId =null;
      getInvByDeptIdAndSalesIdAndClassCode({'deptId':this.form.exDeptId}).then(response => {
         this.materialList = response.data;
      });
    },
    materialChange(data){
      getDeptMaterialInfoByDeptIdAndMaterialId({'deptId':this.form.exDeptId,'materialId':this.form.materialId}).then(response => {
        this.form.packageNum = response.data.packageNum;
        this.form.sheetNum = response.data.sheetNum;
      });

    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加即开票调拨单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInventoryBillJoin(id).then(response => {
        this.form = response.data;
        this.form.stat = response.data.stat + '';
        this.open = true;
        this.title = "修改即开票调拨单";
      });
    },
    handleCheck(row){
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认调拨"' + ids + '"的数据项？').then(function() {
        return check(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("调拨成功");
      }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInventoryBillJoin(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInventoryBillJoin(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除出入库--即开票入库明细编号为"' + ids + '"的数据项？').then(function() {
        return delInventoryBillJoin(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/inventoryBillJoin/export', {
        ...this.queryParams
      }, `inventoryBillJoin_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
